package com.cxd.app.service;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.cxd.app.entity.base.DictBase;
import com.cxd.base.util.BeanTools;

/**
 * <一句话功能简述> <功能详细描述>
 * @author wtj
 * @date 2015年12月8日 上午9:52:45
 * @company CXD
 * @version [Copyright (c) 2015 V001]
 */
@Service("dictService")
public class DictService {
	private static final Logger log = Logger.getLogger(DictService.class);
	@Resource
	public BeanTools bt;
	
	/**
	 * 通过编号获取该编号对应的名称，此处是父key为空的情况下
	 * @param id
	 * @return
	 */
	public  String getValue(String key){
		return getValue(null,key);
	}
	
	/**
	 * 通过数据字典的 父编码和子编码获取对应的名称
	 * @param parentKey
	 * @param key
	 * @return
	 */
	public String getValue(String parentKey ,String key){
		if (StringUtils.isEmpty(key)) {
			return null;
		}
		if(parentKey == null){
			parentKey = "COMMON";
		}
		String sql = "select di2.* from dict di2 left join Dict di1   on di1.id = di2.p_id where di1.`key` = '"+parentKey+"' and di2.`key` = '"+key+"'";
		List<DictBase> dicts = bt.queryListBean(sql, DictBase.class);
		if(dicts.size() > 1){
			log.error("有多个相同的key存在数据库中");
			return "ERROR[多个相同的KEY]";
		}else if(dicts.size() < 1){
			return parentKey +"."+key + " not found";
		}else{
			return dicts.get(0).getValue();
		}
	}
}
